package com.leps.nq.bi;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.leps.nq.bi.mapper.CompanyBIMapper;
import com.leps.nq.bi.vo.*;
import com.leps.nq.bu.mapper.BuCustMapper;
import com.leps.nq.bu.service.IBuWellService;
import com.leps.nq.bu.vo.WellVo;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import com.leps.nq.op.entity.OpAlarm;
import com.leps.nq.op.mapper.OpMonthlyTaskMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = "公司BI看板")
@RequestMapping("/bi-com")
public class CompanyBIController {
    @Autowired
    BuCustMapper custMapper;
    @Autowired
    OpMonthlyTaskMapper monthlyTaskMapper;
    @Autowired
    CompanyBIMapper companyBIMapper;
    @Autowired
    IBuWellService wellService;

    @GetMapping("/wells-for-map")
    @ApiOperation("根据平台id查询井信息(不传参则表示查询前10个井)")
    public R<List<WellVo>> wellsForMap(Integer stationId) {
        List<WellVo> list = this.wellService.getWellsByStationId(stationId);
        return RBuilder.ok(list);
    }

    @GetMapping("/pump-number")
    @ApiOperation("采输事业部泵注数目")
    public R<PumpStatVo> pump() {
        List<Entry<Long>> totals = this.companyBIMapper.selectTotalCount();
        totals.get(0).setItem("totalNumbers");
        totals.get(1).setItem("onlineNumbers");
        totals.get(2).setItem("offlineNumbers");
        List<Map> maps = this.companyBIMapper.selectCountGroupByCustName();
        List<String> custNames = maps.stream().map(map -> String.valueOf(map.get("cust_name"))).collect(Collectors.toList());
        long[] totalNumbers = maps.stream().mapToLong(map -> Convert.toLong(map.get("总泵数"))).toArray();
        long[] onlineNumbers = maps.stream().mapToLong(map -> Convert.toLong(map.get("在线数"))).toArray();
        long[] offlineNumbers = maps.stream().mapToLong(map -> Convert.toLong(map.get("离线数"))).toArray();
        PumpStatVo pumpStatVo = new PumpStatVo(totals, custNames, totalNumbers, onlineNumbers, offlineNumbers);
        return RBuilder.ok(pumpStatVo);
    }

    @GetMapping("/protect-days")
    @ApiOperation("区块管线最长保护天数")
    public R<ProtectStatVo> protect() {
        List<Entry<Integer>> items = this.custMapper.selectProtectStat();
        Entry<Integer> top1 = items.stream().findFirst().orElse(new Entry<Integer>());
        ProtectStatVo protectStatVo = new ProtectStatVo();
        protectStatVo.setItems(items);
        protectStatVo.setTop1(top1);
        return RBuilder.ok(protectStatVo);
    }

    @GetMapping("/repnenish-of-passed-years")
    @ApiOperation("年液统计量")
    public R<ReplenishStatVo> replenishOfPassedYears() {
        List<Entry<Double>> totals = this.companyBIMapper.selectTotalDosagesOfPassed3YearGroupByYear();
        List<String> custNames = this.custMapper.selectCustNameList();
        List<Map> items = this.companyBIMapper.selectDosagesOfPassed3YearsGroupByCustNameAndYear();
        Map<String, List<Map>> groupByYear = items.stream().collect(Collectors.groupingBy(map -> String.valueOf(map.get("year"))));
        int y3 = DateUtil.year(new Date());
        int y2 = y3 - 1;
        int y1 = y2 - 1;
        double[] year1 = groupByYear.get(String.valueOf(y1)).stream().mapToDouble(m -> (double) m.get("dosage")).toArray();
        double[] year2 = groupByYear.get(String.valueOf(y2)).stream().mapToDouble(m -> (double) m.get("dosage")).toArray();
        double[] year3 = groupByYear.get(String.valueOf(y3)).stream().mapToDouble(m -> (double) m.get("dosage")).toArray();
        totals.get(0).setItem("year1");
        totals.get(1).setItem("year2");
        totals.get(2).setItem("year3");
        ReplenishStatVo vo = new ReplenishStatVo();
        vo.setYear1(year1);
        vo.setYear2(year2);
        vo.setYear3(year3);
        vo.setCustNames(custNames);
        vo.setTotals(totals);
        return RBuilder.ok(vo);
    }

    @GetMapping("/monthly-task-completion")
    @ApiOperation("月液量完成百分比")
    public R<MonthlyTaskCompletionStatVo> monthlyTaskCompletion() {
        List<Map> items = this.companyBIMapper.selectMonthlyTaskCompletionOfEveryTeam();
        BigDecimal goal = (BigDecimal) items.stream().map(map -> map.getOrDefault("task_goal", new BigDecimal("0")))
                .reduce(new BigDecimal("0"), (a, b) -> ((BigDecimal) a).add((BigDecimal) b));
        BigDecimal completed = (BigDecimal) items.stream().map(map -> map.getOrDefault("completed_value", new BigDecimal("0")))
                .reduce(new BigDecimal("0"), (a, b) -> ((BigDecimal) a).add((BigDecimal) b));
        List<Entry<String>> teamCompletionPersent = items.stream().map(map -> {
            Entry<String> entry = new Entry<>();
            BigDecimal completion_rate = (BigDecimal) map.get("completion_rate");
            String value = completion_rate != null ? new DecimalFormat("0.00%").format(completion_rate) : "无任务";
            entry.setName(map.get("team_name").toString());
            entry.setValue(value);
            return entry;
        }).collect(Collectors.toList());
        MonthlyTaskCompletionStatVo vo = new MonthlyTaskCompletionStatVo();
        vo.setCompleted(completed);
        vo.setGoal(goal);
        vo.setTeamCompletionPercent(teamCompletionPersent);
        return RBuilder.ok(vo);
    }

    @GetMapping("/today-task-completion")
    @ApiOperation("当日液量完成升")
    public R<TodayTaskCompletionStatVo> todayTaskCompletion() {
        List<Entry<Double>> teamCompletion = this.companyBIMapper.selectTodayTaskCompletionOfEveryTeam();
        Double completed = teamCompletion.stream().map(Entry::getValue).reduce(0d, (a, b) -> a + b);
        TodayTaskCompletionStatVo vo = new TodayTaskCompletionStatVo();
        vo.setTeamCompletion(teamCompletion);
        vo.setCompleted(completed);
        return RBuilder.ok(vo);
    }

    @GetMapping("/alarm")
    @ApiOperation("采输事业部报警日志")
    public R<AlarmStatVo> alarm() {
        List<Map> list = this.companyBIMapper.selectAlarmCountGroupByAlarmType();
        AlarmStatVo vo = new AlarmStatVo();
        vo.setLiquidLevel(Convert.toLong(list.get(0).get("value")));
        vo.setPressure(Convert.toLong(list.get(1).get("value")));
        vo.setFault(Convert.toLong(list.get(2).get("value")));
        vo.setBrokenNetwork(Convert.toLong(list.get(3).get("value")));
        List<OpAlarm> items = this.companyBIMapper.selectNotHandledAlarmTop20();
        vo.setItems(items);
        return RBuilder.ok(vo);
    }

    @GetMapping("/bubble-device")
    @ApiOperation("采输事业部泡排设备数目")
    public R<SimpleChartVo> bubbleDevice() {
        List<String> custNames = this.custMapper.selectCustNameList();
        List<Long> values = this.companyBIMapper.selectBubbleDeviceGroupByCust();
        SimpleChartVo vo = new SimpleChartVo();
        vo.setCustNames(custNames);
        vo.setValues(values);
        return RBuilder.ok(vo);
    }

    @GetMapping("/bubble-dosage")
    @ApiOperation("采输事业部泡排药剂用量")
    public R<SimpleChartVo> bubbleDosage() {
        List<String> custNames = this.custMapper.selectCustNameList();
        List<Long> values = this.companyBIMapper.selectBubbleDosageGroupByCust();
        SimpleChartVo vo = new SimpleChartVo();
        vo.setCustNames(custNames);
        vo.setValues(values);
        return RBuilder.ok(vo);
    }
}
